<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\exchange\Code as LibraryCode;
use app\admin\model\exchange\Library;
use app\admin\model\exchange\Log;
use addons\shopro\model\Order;
use addons\shopro\model\OrderItem;
use app\common\model\User;
use addons\shopro\model\UserAddress;
use app\common\model\User as FUser;
use app\common\model\White;
use fast\Random;
use think\Config;
use think\Db;
use Exception;
use think\exception\PDOException;
use \app\admin\model\share\CommonShare;
use app\admin\model\share\ShareUser;
use app\common\library\Auth;
use app\admin\model\exchange\Goods;
use app\common\model\ScoreLog;
use app\common\model\MoneyLog;
use app\common\library\Sms;
use app\common\model\userIdCard;
use \think\log  as logs;

/**
 * 示例接口
 */
class Coupon extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new LibraryCode;
        $this->goods = new Goods;
        $this->user_id = $this->auth->id;
    }

    /**
     * 提货劵接口：罗列当前我的提货劵  三个状态 未使用 已使用  已过期
     */
    public function lists()
    {
        $where = array('user_id' => $this->user_id);
        $status = $this->request->post("status"); // 状态
        if (!$status) {
            $this->error("状态不能为空");
        }
        $goods_id = $this->request->post("goods_id");
        if (!empty($goods_id)) {
            //$where['goods_id'] = $goods_id;
            //qi10.28
           // $where['goods_id'] = ['in',$goods_id];
        }

        // 金额判断
        $money = $this->request->post("money");
        if (!empty($money)) {
            $where['library.money'] = $money;
        }

        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 20 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $list = $this->model
                ->alias('code')
                ->with(['library'])
                ->where($where)
                ->where('code.status',$status)
                ->order('code.end_time','desc')
                ->limit($page,$limit)->select();

        foreach ($list as $k=>$v){//qi10.28
            $gids = explode(',',$v['library']['goods_id']);
            if(!in_array($goods_id,$gids)){
                unset($list[$k]);
            }
        }

        $this->success('成功', array_values($list));
    }
    public function lists_sum()
    {
        $where = array('user_id' => $this->user_id);
        $status = $this->request->post("status"); // 状态
        if (!$status) {
            $this->error("状态不能为空");
        }
        $goods_id = $this->request->post("goods_id");
        if (!empty($goods_id)) {
            $where['goods_id'] = $goods_id;
        }

        // 金额判断
        $money = $this->request->post("money");
        if (!empty($money)) {
            $where['library.money'] = $money;
        }

        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $list = $this->model
            ->alias('code')
            ->with(['library'])
            ->where($where)
            ->where('code.status',$status)
            ->order('code.end_time','desc')
            ->group('code.library_id')
            ->limit($page,$limit)->select();

        foreach ($list as $k=>$v){
            //增加商品信息
            $list[$k]['goods_title'] = "";
            if (isset($v['goods_id'])){
                $goods = \app\admin\model\shopro\Goods::where(['id'=>$v['goods_id']])->find();
                if($goods){
                    $list[$k]['goods_title'] = $v['title'];
                }
            }
            //增加来源信息
            if($v['order_id']){
                $order = Order::where(['id'=>$v['order_id']])->find();
                if($order){
                    $user = User::where(['id'=>$order->user_id])->find();
                    if($user){
                        $list[$k]['form_mobile'] = $user->mobile;
                    }
                }
            }
            $list[$k]['end_time'] = date('Y-m-d H:i:s',$v['library']['createtime'] + 86400*$v['library']['end_day']);
            $z_shu = DB::name("exchange_code")->where(['user_id'=>$this->user_id,'status'=>$status,'library_id'=>$v['library_id']])->count();
            $list[$k]['k_z_sum'] = $z_shu;
            $z_list = DB::name("exchange_code")->where(['status'=>$status,'library_id'=>$v['library_id']])->select();
            $codes = '';
            foreach ($z_list as $k1=>$v1){
                $codes .= $v1['code'].',';
            }
            $l_where['code'] = ['in',trim($codes,',')];
            $l_where['subgift_user_id'] = $this->user_id;
            $y_z_sum = DB::name("exchange_log")
                ->where($l_where)
                ->count();
            $list[$k]['y_z_sum'] =$y_z_sum;
        }
        $this->success('成功', $list);
    }
    /*public function lists_sum()
    {
        $u = FUser::get($this->auth->id);
        $where = array('goods.mobile' => $u->mobile);
        $status = $this->request->post("status"); // 状态
        if (!$status) {
            $this->error("状态不能为空");
        }
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $list = $this->goods
            ->alias('goods')
            ->with(['library'])
            ->where($where)
            ->order('goods.createtime','desc')
            ->limit($page,$limit)->select();
        foreach ($list as $k=>$v){
           $z_shu = DB::name("exchange_code")->where(['status'=>$status,'good_id'=>$v['id']])->count();

            $s_shu = DB::name("exchange_code")->where(['status'=>$status,'good_id'=>$v['id'],'user_id'=>$this->user_id])->count();
            $code_data = DB::name("exchange_code")->where(['status'=>$status,'good_id'=>$v['id']])->find();
            $list[$k]['k_z_sum'] = $s_shu;
            $list[$k]['end_time'] = $code_data['end_time'];
            $list[$k]['y_z_sum'] = $z_shu - $s_shu;
        }
        $this->success('成功', $list);
    }*/


     /**
     * 转增接口：录入平台存在的手机号，可以转增，否则转增不了
     */
    public function increase()
    {
        $mobile = $this->request->post("mobile"); // 手机号
        $library_id =  $this->request->post("library_id"); // ID
        $sum =  $this->request->post("sum"); // 转让数量
        $captcha = $this->request->post("captcha");//短信验证码
        $k_z_sum = $this->model->where(['library_id'=>$library_id,'user_id'=>$this->auth->id,'status'=>1])->count();
        if($sum > $k_z_sum){
            $this->error(__('可转让数量不够'));
        }
        if (!$captcha) {
            $this->error(__('验证码不能为空'));
        }
        $arr_temp = array(13131388888,
            18213345601,18213345602,18213345603 ,18213345604 ,18213345605 ,18213345606 ,18213345607 ,18213345608 ,18213345609 ,18213345610 ,18213345611 ,18213345612 ,18213345613 ,18213345614 ,18213345615 ,18213345616 ,18213345617 ,18213345619 ,18213345620 ,18213345621 ,18213345622 ,18213345623 ,18213345624 ,18213345625 ,18213345626 ,18213345627,18213345628,13136281919
        );
        $is_true = true;
        if (in_array($this->auth->mobile, $arr_temp)) {
            if ($this->auth->mobile == '13131388888' && $captcha == '131313') {
                $is_true = false;
            }
            if ($this->auth->mobile != '13131388888' && $captcha == '1111') {
                $is_true = false;
            }
        }
        $user = $this->auth->getUser();
        $config_test_code= Db::name("config")->where(['name' => "test_code"])->find();
        $test_code=$config_test_code ? $config_test_code['value'] : 134913;
        if($is_true){
            if($user->staff==2 && $captcha!=$test_code){
                $this->error(__('验证码不正确'));
            }
            if($user->staff!=2){
                if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
                    $this->error(__('验证码不正确'));
                }
            }
        }
        $fttuser =  User::getByMobile($mobile);
        if (empty($fttuser)) {
            $this->error('手机号不存在');
        }
        if ($this->auth->mobile == $mobile) {
            $this->error('自己不能转赠给自己');
        }

        if(($user->staff!=2 && $fttuser["staff"]==2) || ($user->staff==2 && $fttuser["staff"]!=2)){
            $this->error('账号是测试号，无法转增');
        }

        $lists = $this->model->where(['library_id'=>$library_id,'user_id'=>$this->auth->id,'status'=>1])->limit($sum)->order("id asc")->select();
        foreach ($lists as $key => $value) {
            if ($value['user_id'] != $this->user_id) {
                $this->error("不是本用户的提货券");
            }
            if ($value['status'] == 2) {
                $this->error("提货券已使用");
            }
            if ($value['status'] == 3) {
                $this->error("提货券已过期");
            }
        }
        if (empty($lists)) {
            $this->error("提货券不存在");
        }
        $data = array(
            'user_id' =>$fttuser['id'],
            'mobile' =>$mobile,
        );

        $count = 0;
        Db::startTrans();
        try {
            foreach ($lists as &$item) {
                $this->model->where(['id' =>$item['id']])->update($data);
                if ($count == 0) {
                    // 记录
                    $log = array(
                        'subgift_user_id' => $this->user_id,
                        'user_id' => $fttuser['id'],
                        'code_id' => $item['id'],
                        'code' => $item['code'],
                        'sum' => $sum,
                        'batch_code' => Random::alnum(10)
                    );
                    (new Log())->save($log);
                }
                $count += 1;
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('转增成功');
        }
        $this->error('转增失败');
    }

    /**
     * 核销接口，验证提货劵是否有效
     */
    public function writeoff()
    {
       /* $money_exchange = Db::name("config")->where(['name' => 'money_exchange'])->find();
        if($money_exchange && $money_exchange['value'] == 2){
            $this->error(__('亲，此功能暂未开放···'));
        }*/
        $order_sn = $this->request->post("order_sn"); // 订单id
        $code_id =  $this->request->post("code_id"); // ID
        $one_day =  $this->request->post("one_day",0);
        // $total_price =  $this->request->post("total_price"); // 订单总价
        // $goods_id = $this->request->post("goods_id"); // 商品id
        // code_id=2448&goods_id=4&total_price=5999.00&address_id=140&one_day=0
        Db::startTrans();
        try{
            $row = $this->model->lock(true)->where('id','=',$code_id)->find();
            if (empty($row)) {
                throw new Exception("提货券不存在");
            }
            if ($row['status'] == 2) {
                throw new Exception("提货券已使用");
            }
            if ($row['status'] == 3) {
                throw new Exception("提货券已过期");
            }
            if ($row['user_id'] != $this->user_id) {
                throw new Exception("不是本用户的提货券");
            }
             $order = (new Order())->where(['user_id' => $this->user_id,'order_sn' =>$order_sn])->find();
            if (!$order) {
                throw new Exception("订单不存在");
            }
            // $Library = (new Library())->get($row['library_id']);

            // 添加订单
            $data = array(
                'status'  => 1,
                'paytime' => time(),
                'pay_fee' => $order['total_fee'],
                'platform' => 'Coupon',
                'pay_type' => 'shopping',
                'one_day' => $one_day,
            );
            // $order = new Order();
            $order->allowField(true)->save($data);
            // 提交事务


            // 提货券购买记录
            $exchangeGoods = [];
            $exchangeGoods['library_id'] = $row['library_id'];
            $exchangeGoods['num'] = 1;
            $exchangeGoods['user_id'] = $this->user_id;
            $exchangeGoods['name'] = $this->auth->getUserinfo()['nickname'];;
            $exchangeGoods['mobile'] = $this->auth->getUserinfo()['mobile'];;
            $exchangeGoods['money'] = db('exchange_library')->where('id',$row['library_id'])->value('money');
            $exchangeGoods['createtime'] = time();
            $exchangeGoods['batch'] = time();
            $exchangeGoods['remarks'] = '购物消费';
            $exchangeGoods['type'] = 3;
            db('exchange_goods')->insert($exchangeGoods);

            Db::commit();


            $result =$this->model->where(['id' =>$code_id])->update(['status'=>2, 'order_id'=>$order->id]);
            (new CommonShare())->add_share_order($order->id,$order->goods_id,$this->user_id);
            if ($result) {
                if($order->one_day == 1 || $order->one_day == 2){
                    model('addons\shopro\model\ShareReward')->addProfitAmount($order);
                }
            } else {
                throw new Exception("失败");
            }

            // $this->success('成功', $result);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功', $result);
    }
    public function writeoff_bak()
    {

        $address_id =  $this->request->post("address_id"); // ID
        $address = UserAddress::info(['id'=>$address_id]);
        if (empty($address)) {
            $this->error("地址不能为空");
        }
        $real_name = $address["consignee"];//$this->request->post("real_name"); // 收货人姓名
        $user_phone = $address["phone"];//$this->request->post("user_phone"); // 收货人手机号
        $province_name = $address["province_name"];//$this->request->post("province_name"); // 省
        $city_name = $address["city_name"];//$this->request->post("city_name"); // 市
        $area_name = $address["area_name"];//$this->request->post("area_name"); // 区
        $province_id = $address["province_id"];//$this->request->post("province_id"); // 省
        $city_id = $address["city_id"];//$this->request->post("city_id"); // 市
        $area_id = $address["area_id"];//$this->request->post("area_id"); // 区
        $address_detail = $address["address"];//$this->request->post("address_detail"); // 详细地址
        $total_price =  $this->request->post("total_price"); // 订单总价
        $goods_id = $this->request->post("goods_id"); // 商品id
        $code_id =  $this->request->post("code_id"); // ID
        $one_day =  $this->request->post("one_day",0);

        // code_id=2448&goods_id=4&total_price=5999.00&address_id=140&one_day=0
        Db::startTrans();
        try{
            $row = $this->model->lock(true)->where('id','=',$code_id)->find();
            if (empty($row)) {
                throw new Exception("提货券不存在");
            }
            if ($row['status'] == 2) {
                throw new Exception("提货券已使用");
            }
            if ($row['status'] == 3) {
                throw new Exception("提货券已过期");
            }

            if ($row['user_id'] != $this->user_id) {
                throw new Exception("不是本用户的提货券");
            }
            $Library = (new Library())->get($row['library_id']);

            // 添加订单
            $data = array(
                'type' => 'goods',
                'order_sn' => $this->english_num(),
                'user_id' => $this->user_id,
                'goods_amount' => $Library['money'],
                'dispatch_amount' => 0,
                'phone' => $user_phone,
                'consignee' => $real_name,
                'province_name' => $province_name,
                'city_name' => $city_name,
                'area_name' => $area_name,
                'address' => $address_detail,
                'province_id' => $province_id,
                'city_id' => $city_id,
                'area_id' => $area_id,
                'status'  => 1,
                'total_amount' => $total_price,
                'total_fee' => $total_price,
                'goods_id' => $goods_id,
                'discount_fee' => 0,
                'coupon_fee' => 0,
                'pay_fee' => $total_price,
                'goods_original_amount' => $Library['money'],
                'pay_type' => 'wallet',
                'paytime' => time(),
                'platform' => 'Coupon',
                'createtime' => time(),
                'one_day' => $one_day,
            );
            $order = new Order();
            $order->allowField(true)->save($data);
            $detail = \addons\shopro\model\Goods::getGoodsDetail($goods_id);
            $orderItem = new OrderItem();
            $orderItem->user_id = $this->user_id;
            $orderItem->order_id = $order->id;
            $orderItem->goods_id = $goods_id;
            $orderItem->goods_type = 'normal';
            $orderItem->goods_sku_price_id = 0;// 规格id
            $orderItem->activity_id = 0;     // 商品当前的活动类型
            $orderItem->activity_type = null;     // 商品当前的活动类型
            // 当前商品规格对应的 活动下对应商品规格的 id
            $orderItem->item_goods_sku_price_id = 0;
            $orderItem->goods_title = $detail['title'];
            $orderItem->goods_image = $detail['image'];
            $orderItem->goods_original_price = $detail['original_price'];
            $orderItem->pay_price = $total_price;        // 平均计算单件商品不算运费，算折扣时候的金额
            $orderItem->goods_price = $total_price;
            $orderItem->goods_num = 1;
            $orderItem->goods_weight = 0;
            $orderItem->dispatch_status = 0;
            $orderItem->dispatch_fee = 0;
            $orderItem->dispatch_type = 'express';
            $orderItem->dispatch_id = 0;
            $orderItem->store_id = 0;
            $orderItem->aftersale_status = 0;
            $orderItem->comment_status = 0;
            $orderItem->refund_status = 0;
            $ext = [];
            $orderItem->ext = json_encode($ext);
            $orderItem->save();
            $result =$this->model->where(['id' =>$code_id])->update(['status'=>2, 'order_id'=>$order->id]);
            (new CommonShare())->add_share_order($order->id,$goods_id,$this->user_id);
            if ($result) {
                if($order->one_day == 1 || $order->one_day == 2){
                    model('addons\shopro\model\ShareReward')->addProfitAmount($order);
                }
            } else {
                throw new Exception("失败");
            }
            // 提交事务
            Db::commit();
            // $this->success('成功', $result);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功', $result);
        $this->success('返回成功', ['action' => 'test1']);
    }

    private function english_num()
    {
        $s = '0123456789';
        $temp = '';
        while (strlen($temp) < 32) {
            $index = mt_rand(0, strlen($s) - 1);
            $temp .= $s[$index];
        }
        return $temp;
    }

    // 确认收货
    public function confirm()
    {
        $order_id =  $this->request->post("order_id"); // ID
        $order = (new Order())->get($order_id);
        if (empty($order)) {
            $this->error("订单不存在");
        } else {
            $order->status = 2;
            $order->save();
            Db::name("shopro_order_item")->where(["order_id"=>$order_id])->update(["dispatch_status"=>2]);
            $this->success('收货成功');
        }

    }

     /**
     * 提货券列表
     */
    public function coupon_list()
    {
        $where['is_delete'] = 0;
        $where['money'] = ['>=',1000];
        $where['id'] = ['not in',[14]];
        $lists = (new Library())->where($where)->select();
        $data =  [];
        foreach ($lists as $key => $value) {
            $d = date('Y-m-d H:i:s',time());
            $code_where['library_id'] = $value['id'];
            $code_where['status'] = 0;
            $code_where['end_time'] = ['<',$d];
            $code_count = (new LibraryCode)->where($code_where)->count();
            if ($code_count > 0) {
                $value['money'] = round($value['money']);
                $temp = $value;
                $temp['code_count'] = $code_count;
                $data[] = $temp;
            }
        }

        $this->success('成功', $data);
    }

    /**
     * 积分兑换提货券
     */
    public function exchange_coupon()
    {
        $ws = Db::name("config")->where(['name' => 'score_exchange'])->find();
        if (!$ws || $ws['value'] == '') {
            $this->error(__('该权限关闭，开通另行通知！'));
        } else {
            if ($ws['value'] != 1) {
                $this->error(__('该权限关闭，开通另行通知！'));
            }
        }
        $library = $_POST["library"];
        //$library =  '[{"id":"1","num":"1"}]';
        $libraryList = json_decode($library,TRUE);
        $temp_score = 0;
        if (empty($library)) {
            $this->error('提货券不能为空');
            return;
        }
        foreach ($libraryList as $key => $value) {
            $temp_Library = (new Library())->get(['id'=>$value['id'], 'is_delete' =>0]);
            if(empty($temp_Library)){
                $this->error('提货券不存在');
                return;
            }
            $code_temp = (new LibraryCode)->where(['library_id'=> $value['id'], 'status' => 0])->select();
            if (empty($code_temp)) {
                $this->error("提货券数量不足，请联系管理员");
                return;
            }
            if (count($code_temp) <= (int)$value['num']) {
                $this->error("提货券数量不足，请联系管理员");
                return;
            }
            $temp_score = bcadd($temp_score,bcmul($temp_Library['money'], $value['num']));
        }
        $share_user =(new ShareUser())->get(['user_id'=>$this->auth->id]); // 用户积分
        if((double)$share_user['score'] < (double)$temp_score){
            $this->error('积分不足');
        }
        foreach ($libraryList as $key => $value) {
            $this->addLibraryCode($value['id'],$value['num']);
        }

        $this->success('兑换成功');
    }

    /**
     * 添加券
     */
    public function addLibraryCode($library_id,$num)
    {
        $code_temp = (new LibraryCode)->where(['library_id'=> $library_id, 'status' => 0])->select();
        $Library = (new Library())->get(['id'=>$library_id, 'is_delete' =>0]);
        $share_user =(new ShareUser())->get(['user_id'=>$this->auth->id]); // 用户积分
        $temp_score = bcmul($Library['money'],$num);
        $end_time = date('Y-m-d',strtotime('+'.$Library['end_day'].' day'));
        $goods = (new Goods());
        $goods->name = $this->auth->nickname;
        $goods->mobile = $this->auth->mobile;
        $goods->library_id = $library_id;
        $goods->num = $num;
        $goods->money = $temp_score;
        $goods->remarks = '积分兑换';
        $goods->user_id = $this->auth->id;
        $goods->createtime = time();
        $goods->save();

        $Library->status = 1;
        $Library->save();
        foreach ($code_temp as $key => $value) {
            if ($key < (int)$num) {
                $data = array(
                    'status' => 1,
                    'user_id' =>$this->auth->id,
                    'name' => $this->auth->nickname,
                    'mobile' => $this->auth->mobile,
                    'good_id' =>  $goods->id,
                    'end_time' => $end_time
                );
                (new LibraryCode)->where(['id' =>$value['id']])->update($data);
            }
        }
        $before = $share_user->score;
        $after = $share_user->score - $temp_score;
        $share_user->score = $after;
        $share_user->save();
        $this->add_sorc($this->auth->id,$temp_score,$before,$after,$Library->name,'',5);
    }

    /**
     * 积分转赠
     */
    public function score_subgift()
    {
        $users =  User::get($this->auth->id);
        /*if($users['mobile'] != '13131388888'){
            if($_SERVER['HTTP_HOST'] != 'zhongjunf.bigchun.com'){
                $this->error(__('该权限关闭，开通另行通知！'));
            }

        }*/

        $mobile = $this->request->post("mobile"); // 手机号
        $score = $this->request->post("score"); // 积分
        $captcha = $this->request->post("captcha");//短信验证码
        if (!$captcha) {
            $this->error(__('验证码不能为空'));
        }
        $config_test_code= Db::name("config")->where(['name' => "test_code"])->find();
        $test_code=$config_test_code ? $config_test_code['value'] : 134913;
        if (!White::verifyMobileWhite($this->auth->mobile, $captcha)) {
            $arr_temp = array(13131388888,
                18213345601,18213345602,18213345603 ,18213345604 ,18213345605 ,18213345606 ,18213345607 ,18213345608 ,18213345609 ,18213345610 ,18213345611 ,18213345612 ,18213345613 ,18213345614 ,18213345615 ,18213345616 ,18213345617 ,18213345619 ,18213345620 ,18213345621 ,18213345622 ,18213345623 ,18213345624 ,18213345625 ,18213345626 ,18213345627,18213345628,13136281919
            );
            $is_true = true;
            if (in_array($this->auth->mobile, $arr_temp)) {
                if ($this->auth->mobile == '13131388888' && $captcha == '131313') {
                    $is_true = false;
                }
                if ($this->auth->mobile != '13131388888' && $captcha == '1111') {
                    $is_true = false;
                }
            }
            if($is_true){
                if($users->staff==2 && $captcha!=$test_code){
                    $this->error(__('验证码不正确'));
                }
                if($users->staff!=2){
                    if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
                        $this->error(__('验证码不正确'));
                    }
                }
            }
        }

        $fttuser =  User::getByMobile($mobile);
        if (empty($fttuser)) {
            $this->error('手机号不存在');
        }

        if ($fttuser['id'] == $this->auth->id) {
            $this->error('自己不能给自己转赠');
        }
        if(($users["staff"]==2 && $fttuser['staff']!=2) || ($users["staff"]!=2 && $fttuser['staff']==2) ){
            $this->error('此账号是测试号，无法转增');
        }
        if(empty($score)){
            $this->error('转赠积分需要大于0积分');
        }
        $share_user =(new ShareUser())->get(['user_id'=>$this->auth->id]); // 用户积分
        if((double)$share_user['score'] < (double)$score){
            $this->error('积分不足');
        }
        $before1 = $share_user->score;
        $after1 = $share_user->score - $score;
        $share_user->score = $after1;
        $share_user->save();
        $subgift_user =(new ShareUser())->get(['user_id'=>$fttuser['id']]); // 转赠用户
        $before = $subgift_user->score;
        $after = $subgift_user->score + $score;
        $subgift_user->score = $after;
        $subgift_user->save();

        $this->add_sorc($fttuser['id'],$score,$before,$after,'转赠人：'.$users['mobile'],$users['mobile'],6);//增加
        $this->add_sorc($this->auth->id,$score,$before1,$after1,'转赠对象：'.$mobile,$mobile,6);//减少
        $this->success('转赠成功');
    }

    public function add_sorc($user_id,$score,$before,$after,$memo,$mobile = '',$type=0)
    {
        ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo, 'type' => $type,'mobile'=>$mobile]);
    }

    /**
     * 积分提现
     */
    public function score_withdrawal()
    {
       $users =  User::get($this->auth->id);
        if($users['mobile'] != '13131388888'){
            $this->error('该权限关闭，开通另行通知！');
        }
        /*
               $score = $this->request->post("score"); // 积分
               if(empty($score)){
                   $this->error('转赠积分需要大于0积分');
               }
               $star_time = date('Y-m-d 00:00:00');
               $end_time = date('Y-m-d 23:59:59');
               $score_sum = (new ScoreLog())->where(['user_id'=> $this->auth->id])->where('createtime', 'between time', [$star_time, $end_time])->where(['type'=>7])->sum('score');
               if (!empty($score_sum)) {
                   $this->error('每天最多兑换1次');
               }
               if((int)$score > 300){
                   $this->error('每天最多兑换300积分');
               }
               $m_day = strtotime(date('Y-m',time()));
               $r_where['user_id'] = $this->auth->id;
               $r_where['createtime'] = ['>',$m_day];
               $r_where['one_day'] = 1;
               $r_where['status'] = ['in','1,2'];
               $r_where['share_retreat'] = ['neq',2];
               $r_data = Db::name("shopro_order")->where($r_where)->find();

               $one_day_order = 1;
               $c_data =  Db::name("config")->where(['name'=>'withdraw_sta','value'=>1])->find();//中慧特殊配置
               if (empty($r_data)) {
                   $share_data = Db::name("share_user")->where(['user_id'=>$this->auth->id])->find();
                   $one_day_order = 0;
                   if($c_data && $share_data['is_order'] == 0){//中慧新客户不限制
                       $one_day_order = 1;
                   }

               }
               if ($one_day_order == 0) {
                   $this->error("购买一次每月一品才能提现");
               }
               $share_user =(new ShareUser())->get(['user_id'=>$this->auth->id]); // 用户积分
               if((double)$share_user['score'] < (double)$score){
                   $this->error('积分不足');
               }
               $before1 = $share_user->score;
               $after1 = $share_user->score - $score;
               $share_user->score = $after1;
               $share_user->total_price += $score;
               $share_user->price += $score;
               $share_user->save();
               $this->add_sorc($this->auth->id,$score,$before1,$after1,'积分提现','',7);*/
        $this->success('成功');
    }

    /**
     * 积分转赠验证手机号
     */
    public function verify_mobile()
    {
        $mobile = $this->request->post("mobile"); // 手机号
        $fttuser =  User::getByMobile($mobile);
        if (empty($fttuser)) {
            $this->error('手机号不存在');
        }
        $idCardData = userIdCard::where('user_id', '=', $fttuser->id)->find();
        $name = empty($idCardData) ?  $fttuser['nickname'] : $idCardData['name'];

        $this->success('成功', array('name'=>$name,'mobile'=>$mobile));
    }

    /**
     * 我的转赠记录
     */
    public function my_score_log()
    {
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $list = (new ScoreLog())
                ->where(['user_id'=>$this->user_id])
                ->where('mobile','<>','')
                ->order('createtime','desc')
                ->limit($page,$limit)->select();
        foreach ($list as $key => &$value) {
            $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }

        $this->success('成功', $list);
    }

    /**
     * 余额兑换提货券
     */
    public function money_coupon()
    {
        $money_exchange = Db::name("config")->where(['name' => 'money_exchange'])->find();
        if($money_exchange && $money_exchange['value'] == 2){
            $this->error(__('亲，此功能暂未开放···'));
        }
        $library = $_POST["library"];
        //$library =  '[{"id":"1","num":"1"}]';
        $libraryList = json_decode($library,TRUE);
        $temp_money = 0;
        if (empty($library)) {
            $this->error('提货券不能为空');
            return;
        }
        foreach ($libraryList as $key => $value) {
            $temp_Library = (new Library())->get(['id'=>$value['id'], 'is_delete' =>0]);
            if(empty($temp_Library)){
                $this->error('提货券不存在');
                return;
            }
            $code_temp = (new LibraryCode)->where(['library_id'=> $value['id'], 'status' => 0])->select();
            if (empty($code_temp)) {
                $this->error("提货券数量不足，请联系管理员");
                return;
            }
            if (count($code_temp) <= (int)$value['num']) {
                $this->error("提货券数量不足，请联系管理员");
                return;
            }
            $temp_money = bcadd($temp_money,bcmul($temp_Library['money'], $value['num']));
        }
        $share_user =(new ShareUser())->get(['user_id'=>$this->auth->id]); // 用户余额
        if((double)$share_user['price'] < (double)$temp_money){
            $this->error('余额不足');
        }
        foreach ($libraryList as $key => $value) {
            $this->addLibraryCodeMoney($value['id'],$value['num']);
        }

        $this->success('兑换成功');
    }

    /**
     * 添加券
     */
    public function addLibraryCodeMoney($library_id,$num)
    {
        $code_temp = (new LibraryCode)->where(['library_id'=> $library_id, 'status' => 0])->select();
        $Library = (new Library())->get(['id'=>$library_id, 'is_delete' =>0]);
        $share_user =(new ShareUser())->get(['user_id'=>$this->auth->id]); // 用户积分
        $temp_money = bcmul($Library['money'],$num);
        $end_time = date('Y-m-d',strtotime('+'.$Library['end_day'].' day'));
        $goods = (new Goods());
        $goods->name = $this->auth->nickname;
        $goods->mobile = $this->auth->mobile;
        $goods->library_id = $library_id;
        $goods->num = $num;
        $goods->money = $temp_money;
        $goods->remarks = '余额兑换';
        $goods->user_id = $this->auth->id;
        $goods->createtime = time();
        $batch = time().$this->auth->id;
        $goods->batch = $batch;
        $goods->type = 1;
        $goods->save();

        $Library->status = 1;
        $Library->save();
        foreach ($code_temp as $key => $value) {
            if ($key < (int)$num) {
                $data = array(
                    'status' => 1,
                    'user_id' =>$this->auth->id,
                    'name' => $this->auth->nickname,
                    'mobile' => $this->auth->mobile,
                    'good_id' =>  $goods->id,
                    'end_time' => $end_time,
                );
                (new LibraryCode)->where(['id' =>$value['id']])->update($data);
            }
        }
        $before = $share_user->price;
        $after = $share_user->price - $temp_money;
        $share_user->price = $after;
        $share_user->save();
        MoneyLog::create(['user_id' => $this->auth->id, 'money' => $temp_money, 'before' => $before, 'after' => $after, 'type' => 5, 'memo' => '余额兑换提货券']);
    }
    public function exchange_log(){
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 :  bcmul($offset,$limit);
        $where['subgift_user_id'] = $this->user_id;

        $lists = Db::name("exchange_log")->where($where)
            ->order('id', 'DESC')
            ->group("batch_code")
            ->limit($page,$limit)->select();
        foreach ($lists as $key => $value) {
            //$lists[$key]->type_name =  $this->get_type($value->type);
            $lists[$key]['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
            $u = Db::name('user')->field("mobile")->where(['id'=>$value['user_id']])->find();
            $lists[$key]['mobile'] = $u['mobile'];
            $code = Db::name("exchange_code")->where(['id'=>$value['code_id']])->find();
            $library = Db::name("exchange_library")->where(['id'=>$code['library_id']])->find();
            $lists[$key]['name'] = $library['name'];
        }
        $this->success('成功', $lists);
    }
    /**
     *余额兑换记录
     */
    public function exchangeLog(){
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $offset = $this->request->post("offset"); // 第几页
        $limit = 10;
        $where['type'] = 1;
        $where['user_id'] = $this->user_id;
        $lists = Db::name("exchange_goods")->where($where)
            ->whereBetween("createtime",[$srart,$end])
            ->order('id', 'DESC')
//            ->group("batch")
            ->limit(($offset-1)*$limit,$limit)->select();
        $re_data = [];
        foreach ($lists as $k=>$v){
            $name = Db::name("exchange_library")->where(['id'=>$v['library_id']])->find();
            $count = Db::name("exchange_goods")->where(['batch'=>$v['batch']])->count();
//            $money = Db::name("exchange_goods")->where(['batch'=>$v['batch']])->sum("money");
            $re_data[] = [
                "sum"=>$v['num'],
                "money"=>$v['money'],
                "name"=>$name['name'],
                "total_money"=>bcmul($v['money'],$v['num'],2),
                "time"=>date('Y-m-d H:i:s',$v['createtime']),
            ];
        }
        $this->success('成功', $re_data);
    }

    /**
     * 提货券明细
     */
    public function codeOrderDetail()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);

        $offset = $this->request->post("offset"); // 第几页
        $all = $this->request->post("type"); // 总明细all 、下单明细0 转增明细1
        if ($all && $all == 'all') {
            // 转赠转入明细
            $list = db('exchange_log')->where('user_id|subgift_user_id',$this->user_id)->whereBetween("createtime",[$srart,$end])->order('createtime desc')->select();
            foreach ($list as &$v) {
                if ($v['subgift_user_id'] != $this->user_id) {
                    $v['type'] = '核销券转入';
                    $v['mobile'] = db('user')->where('id',$v['subgift_user_id'])->value('mobile');
                    $v['flag'] = '+';
                    $v['type_value'] = 'add';
                } else {
                    $v['type'] = '核销券转赠';
                    $v['mobile'] = db('user')->where('id',$v['user_id'])->value('mobile');
                    $v['mobile'] = substr_replace($v['mobile'],'****',3,4);
                    $v['flag'] = '-';
                    $v['type_value'] = 'reduce';
                }
                $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                $library_id = db('exchange_code')->where('id',$v['code_id'])->value('library_id');
                $ex = db('exchange_library')->where('id',$library_id)->find();
                $v['name'] = $ex['name'];
                $v['money'] = $ex['money'];

                unset($v['subgift_user_id']);
                unset($v['code']);
                unset($v['code_id']);
                unset($v['batch_code']);
                unset($v['user_id']);
            }
            // 提货券明细
            $lists = Db::name("exchange_goods")
                ->where('user_id',$this->user_id)
                ->whereBetween("createtime",[$srart,$end])
                ->order('createtime desc')
                ->select();
            foreach ($lists as &$v){
                $name = Db::name("exchange_library")->where(['id'=>$v['library_id']])->find();
                $v['goods_title'] = "";
                if(isset($name->goods_id)){
                    $goods = \app\admin\model\shopro\Goods::where(['id'=>$name->goods_id])->find();
                    $v['goods_title'] = $goods['title'];
                }
                $v['name'] = $name['name'];
                $v['type_value'] = 'exchange';
                $v['flag'] = '+';
                if ($v['type'] == 0) {
                    $v['type'] = '积分兑换转入';
                } elseif ($v['type'] == 1) {
                    $v['type'] = '余额兑换转入';
                } elseif ($v['type'] == 2) {
                    $v['type'] = '退货退回';
                } else {
                    $v['type'] = '购物消费';
                    $v['type_value'] = 'shop';
                    $v['flag'] = '-';
                }

                $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);

                unset($v['library_id']);
                unset($v['remarks']);
                unset($v['user_id']);
                unset($v['batch']);
            }
            $list = array_merge($list,$lists);
            if (!count($list)) {
                $list = [];
            } else {
                if (isset(array_chunk($list,10)[$offset-1])) {
                    $list = array_chunk($list,10)[$offset-1];
                } else {
                    $list = [];
                }

                array_multisort(array_column($list,'createtime'),SORT_DESC,$list);
            }
        } elseif ($all && $all == 1){
            // 转赠转入明细
            $list = db('exchange_log')->where('user_id|subgift_user_id',$this->user_id)->whereBetween("createtime",[$srart,$end])->order('createtime desc')->select();
            foreach ($list as &$v) {
                if ($v['subgift_user_id'] != $this->user_id) {
                    $v['type'] = '核销券转入';
                    $v['mobile'] = db('user')->where('id',$v['subgift_user_id'])->value('mobile');
                    $v['flag'] = '+';
                    $v['type_value'] = 'add';
                } else {
                    $v['type'] = '核销券转赠';
                    $v['mobile'] = db('user')->where('id',$v['user_id'])->value('mobile');
                    $v['mobile'] = substr_replace($v['mobile'],'****',3,4);
                    $v['flag'] = '-';
                    $v['type_value'] = 'reduce';
                }
                $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                $library_id = db('exchange_code')->where('id',$v['code_id'])->value('library_id');
                $ex = db('exchange_library')->where('id',$library_id)->find();
                $v['name'] = $ex['name'];
                $v['money'] = $ex['money'];

                unset($v['subgift_user_id']);
                unset($v['code']);
                unset($v['code_id']);
                unset($v['batch_code']);
                unset($v['user_id']);
            }
            if (!count($list)) {
                $list = [];
            } else {
                if (isset(array_chunk($list,10)[$offset-1])) {
                    $list = array_chunk($list,10)[$offset-1];
                } else {
                    $list = [];
                }
                array_multisort(array_column($list,'createtime'),SORT_DESC,$list);
            }
        }else {
            $list = Db::name("exchange_goods")
                ->where('user_id',$this->user_id)
                ->where('type',3)
                ->whereBetween("createtime",[$srart,$end])
                ->limit(($offset-1)*10,10)
                ->order("createtime desc")
                ->select();
            foreach ($list as &$v){
                $name = Db::name("exchange_library")->where(['id'=>$v['library_id']])->find();
                $v['name'] = $name['name'];
                $v['type'] = '购物消费';
                $v['type_value'] = 'shop';
                $v['flag'] = '-';
                $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                unset($v['library_id']);
                unset($v['remarks']);
                unset($v['user_id']);
                unset($v['batch']);
            }

        }
        $this->success('成功', $list);
    }
}
